part of base.widgets;

class ToggleBar extends StatefulWidget {
  final double width;
  final double height;
  final double thumbSize;
  final bool value;
  final ValueChanged<bool> onChanged;
  final Color activeTrackColor;
  final Color inactiveTrackColor;
  final Color activeThumbColor;
  final Color inactiveThumbColor;
  final TextStyle textStyle;
  final String? text;

  ToggleBar({
    Key? key,
    this.width = 60.0,
    this.height = 30.0,
    this.thumbSize = 26.0,
    this.value = false,
    required this.onChanged,
    this.activeTrackColor = Colors.green,
    this.inactiveTrackColor = Colors.grey,
    this.activeThumbColor = Colors.white,
    this.inactiveThumbColor = Colors.white,
    this.textStyle = const TextStyle(color: Colors.white),
    this.text,
  }) : super(key: key);

  @override
  _CustomToggleState createState() => _CustomToggleState();
}

class _CustomToggleState extends State<ToggleBar> {
  late bool _value;

  @override
  void initState() {
    super.initState();
    _value = widget.value;
  }

  @override
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _handleTap(),
      child: Container(
        width: widget.width,
        height: widget.height,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(widget.height / 2),
          color: _value ? widget.activeTrackColor : widget.inactiveTrackColor,
        ),
        child: Stack(
          children: [
            AnimatedPositioned(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              left: _value ? widget.width - widget.thumbSize - 2 : 2,
              top: (widget.height - widget.thumbSize) / 2,
              child: AnimatedContainer(
                duration: Duration(milliseconds: 300),
                width: widget.thumbSize,
                height: widget.thumbSize,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: _value
                      ? widget.activeThumbColor
                      : widget.inactiveThumbColor,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      offset: Offset(0, 2),
                      blurRadius: 2,
                      spreadRadius: 1,
                    ),
                  ],
                ),
              ),
            ),
            if (widget.text != null) ...[
              Center(
                child: Text(
                  widget.text ?? "",
                  style: widget.textStyle,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  void _handleTap() {
    setState(() {
      _value = !_value;
    });

    widget.onChanged(_value);
  }
}
